package com.wodan.zhongjinjicang.common.orm.command.read;

import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.Callable;

import com.wodan.zhongjinjicang.common.orm.RdsCommonReadDao;
import com.wodan.zhongjinjicang.common.orm.command.base.AbstractSqlCommandExecutor;
import com.wodan.zhongjinjicang.common.orm.metadata.MethodMetaData;
import com.wodan.zhongjinjicang.common.orm.metadata.TableFieldMetaData;
import com.wodan.zhongjinjicang.common.orm.metadata.TableMetaData;
import com.wodan.zhongjinjicang.common.orm.utils.ReflectionUtils;
import com.wodan.zhongjinjicang.common.orm.utils.SqlGenernateUtils;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;



/**
 * 插入操作的执行者
 * 
 * @ClassName: SqlInsertExecutor
 * @author Administrator
 * @date 2015-11-5 下午4:43:12
 * @history
 * 
 */
public class SqlQueryByIdExecutor extends AbstractSqlCommandExecutor {
	@Override
	protected Object doExecute(final TableMetaData tableMetaData, MethodMetaData methodMetaData, Object[] args) {
		Assert.notEmpty(args);
		Assert.isTrue(args.length == 1);

		// 解析id字段
		final Long id = (Long) args[0];

		// 从表中获取id字段
		TableFieldMetaData idField = tableMetaData.getIdField();

		// 创建sql语句的必须元素
		final String tableName = tableMetaData.getTableName();
		final String[] resultColumns = tableMetaData.getAllColumnNames();
		final String[] conditionColumns = new String[] { idField.getColumnName().toString() };
		final Object[] conditionValue = new Object[] { id };

		// 生成sql语句
		final String sql = super.createCachedSqlScript(new Callable<String>() {

			@Override
			public String call() throws Exception {
				return SqlGenernateUtils.createQuerySql(tableName, resultColumns, conditionColumns);
			}
		}, tableName, resultColumns, conditionColumns);

		// 执行sql语句
		List<Object> resultList = jdbcTemplate.query(sql, conditionValue, new BeanRowMapper(tableMetaData,
				typeHandlerRegistry));

		if (CollectionUtils.isEmpty(resultList)) {
			return null;
		}

		if (resultList.size() > 1) {
			throw new IllegalStateException("selectById方法查询返回[" + resultList.size() + "]行数据，只能返回1行数据");
		}

		return resultList.get(0);
	}

	@Override
	public Method getProxyMethod() {
		return ReflectionUtils.findMethod(RdsCommonReadDao.class, "selectById", Long.class);
	}

	@Override
	protected boolean isEntityMustHaveIdField() {
		return true;
	}

	@Override
	public SqlCommandType getSqlCommandType() {
		return SqlCommandType.SELECT;
	}
}
